﻿import re
import requests
from urllib import error
from bs4 import BeautifulSoup
import os
import imghdr
from sys import argv

# 初始化数据
num = 0
numPicture = 0
file = ''


# 字节bytes转化kb\m\g
def formatSize(bytes):
    try:
        bytes = float(bytes)
        kb = bytes / 1024
    except:
        print("传入的字节格式不对")
        return "Error"

    return kb


# 获取文件大小
def getDocSize(path):
    try:
        size = os.path.getsize(path)
        return formatSize(size)
    except Exception as err:
        print(err)


# 下载图片
def dowmloadPicture(html, keyword):
    global num
    # 利用正则表达式找到图片url
    pic_url = re.findall('"objURL":"(.*?)",', html, re.S)

    for each in pic_url:
        each = each + '.jpg'
        each = each.replace('\\', '')
        print(each)
        try:
            if each is not None:
                pic = requests.get(each, timeout=10)
            else:
                continue
        except BaseException:
            continue
        else:
            string = file + r'\\' + date + keyword + '_baidu_' + str(num) + '.jpg'
            print(string)
            fp = open(string, 'wb')
            fp.write(pic.content)
            fp.close()
            numkb = getDocSize(string)
            if imghdr.what(string)== None or numkb < 10:
                os.remove(string)
            else:
                num += 1
        if num >= numPicture:
            return


def func(typer):
    global num
    global file
    global word
    global numPicture
    global date
    # 从命令行获取关键字、图片数量与保存路径
    word = typer[0]
    numPicture = typer[1]
    file = typer[2]
    date = typer[3]
    num = 0

    # 指定网页地址是 搜狗图片 ， "query=" 是搜索的关键字
    url = 'http://image.baidu.com/search/flip?tn=baiduimage&ie=utf-8&word=' + word + '&pn='

    page = 0



    # 开始下载图片
    while num < numPicture:
        result = requests.get(url + str(page), timeout=10)
        dowmloadPicture(result.text, word)
        page += 60
